package task

import (
	"errors"
	"fmt"
	"github.com/RichardKnop/machinery/v2/log"
	"github.com/RichardKnop/machinery/v2/tasks"
	"time"
)

/* 触发执行Add异步任务 */
func TaskAdd(a, b int64) {
	signature := &tasks.Signature{
		Name: "add",
		Args: []tasks.Arg{
			{
				Type:  "int64",
				Value: a,
			},
			{
				Type:  "int64",
				Value: b,
			},
		},
	}
	_, err := AsyncTaskCenter.SendTask(signature) // 任务可以通过将Signature的实例传递给Server实例来调用
	if err != nil {
		fmt.Println(err)
	}
}

func MyTask(args ...int64) (int64, error) {
	if len(args) == 0 {
		return 0, errors.New("no arguments provided")
	}

	var sum int64
	for _, num := range args {
		sum += num
	}
	time.Sleep(60 * time.Second)
	return sum, nil
}

func TaskAdd2() (taskId string) {
	// 注册任务
	AsyncTaskCenter.RegisterTasks(map[string]interface{}{
		"MyTask": MyTask,
	})
	task := tasks.Signature{
		Name: "MyTask",
		Args: []tasks.Arg{
			{
				Type:  "int64",
				Value: int64(1),
			},
			{
				Type:  "int64",
				Value: int64(2),
			},
		},
	}

	res, err := AsyncTaskCenter.SendTask(&task)
	if err != nil {
		log.ERROR.Printf("Could not send task: %v", err)
		return
	} else {
		fmt.Println("任务创建成功:", res.Signature.UUID)
	}

	return res.Signature.UUID
}

func GetState(taskId string) (status *tasks.TaskState, err error) {
	status, err = AsyncTaskCenter.GetBackend().GetState(taskId)
	return
}
